package chen.web.controller.forum.validator;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class ExcludeValidator implements ConstraintValidator<Exclude, String> {

	private Pattern pattern = null;
	
	@Override
	public void initialize(Exclude exclude) {
		// TODO Auto-generated method stub
		URL source = this.getClass().getResource(exclude.value());
		if(source == null){
			throw new RuntimeException("找不到文件:"+ exclude.value());
		}
		String path = source.getPath();
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(path);
			InputStreamReader reader = new InputStreamReader(fis, "UTF-8");
			BufferedReader br = new BufferedReader(reader);
			StringBuffer sb = new StringBuffer();
			for(String line=br.readLine(); line!=null; line=br.readLine()){
				line = line.replaceAll("\\*", ".*");
				sb.append(line).append("|");
			}
			if(sb.length() > 0){
				sb.deleteCharAt(sb.length()-1);
			}
			br.close();
			reader.close();
			fis.close();
			pattern = Pattern.compile(sb.toString());
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			throw new RuntimeException(e);
		}
	}

	@Override
	public boolean isValid(String obj, ConstraintValidatorContext context) {
		// TODO Auto-generated method stub
		Matcher matcher = pattern.matcher(obj);
		if(matcher.matches()){
			return false;
		}
		return true;
	}


}
